<?php
namespace app\console;

use think\console\Command;
use think\console\Input;
use think\console\Output;

/**
 * TCP 服务端
 * php think Remote
 */
class Tcp extends Command
{
    protected function configure()
    {
       $this->setName('Tcp')->setDescription('Start Tcp Server!');
    }

    protected function execute(Input $input, Output $output)
    {
        $serv = new \swoole_server('0.0.0.0', 9503);

		/*$serv->set([  
            'worker_num' => 1, //一般设置为服务器CPU数的1-4倍
            'daemonize' => 0, //以守护进程执行
            'max_request' => 10000,
            'dispatch_mode' => 2,
            'task_worker_num' => 8, //task进程的数量
            "task_ipc_mode " => 3, //使用消息队列通信，并设置为争抢模式
            //"log_file" => "log/taskqueueu.log", //日志
		]);*/

        $serv->on('connect', function ($serv, $fd){
            echo $fd.'-已经连接：'.date('Y-m-d H:i:s').PHP_EOL;
        });

        $serv->on('receive', function($serv, $fd, $from_id, $data) {
            $binStr = bin2hex($data);
            // todo
            echo $data;

            //获取所有客户端
            foreach ($serv->connections as $fd) {
                $serv->send($fd, $fd.'说：'.$data);
            }

            // $serv->send($fd, $data); //回复
            echo $fd.'-执行结束：'.date('Y-m-d H:i:s').PHP_EOL;
            // $serv->close($fd);
        });

        $serv->on('close', function ($serv, $fd) {
            echo "connection close: {$fd}\n";
        });

        $serv->on('Start', function($serv) {
            echo "Start\n";
            cli_set_process_title("tcp_master");
        });

        $serv->start();
    }
}